package vn.candyapp.qlct.adapter;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;

import vn.candyapp.qlct.R;
import vn.candyapp.qlct.database.DBAdapter;
import vn.candyapp.qlct.database.model.Account;
import vn.candyapp.qlct.database.model.AccountList;
import android.content.Context;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class AccountAdapter extends BaseAdapter {

	private Handler mHandler;
	private LayoutInflater mLayoutInflater;
	private Context mContext;
	private AccountList accountList;
	
	public AccountAdapter(Context context) {
		mLayoutInflater = LayoutInflater.from(context);
		mHandler = new Handler();
		mContext = context;
	}
	
	@Override
	public int getCount() {
		return accountList.getAccountList().size();
	}
	
	public void loadData(final Runnable run) {
		 DBAdapter dbAdapter = new DBAdapter(mContext);
		 accountList = dbAdapter.getAccounts();
		 mHandler.post(run);
	}

	@Override
	public Object getItem(int position) {
		return accountList.getAccountAtPosition(position);
	}

	@Override
	public long getItemId(int position) {
		return accountList.getAccountList().size();
	}
	
	public String getTotalSum() {
		float balance = 0;
		for (Account acc : accountList.getAccountList()) {
			balance += acc.getBalance();
		}
		return int2CurrencyStr(Float.valueOf(balance).intValue());
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		if (convertView == null) {
			convertView = mLayoutInflater.inflate(R.layout.account_list_item, parent, false);
			holder = new ViewHolder();
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		holder.tvName = (TextView) convertView.findViewById(R.id.tvAccountName);
		holder.tvBalance = (TextView) convertView.findViewById(R.id.tvAccountBalance);
		
		Account acc = (Account) getItem(position);
		holder.tvBalance.setText(int2CurrencyStr(Float.valueOf(acc.getBalance()).intValue()));
		holder.tvName.setText(acc.getName());
		
		return convertView;
	}
	
	public String int2CurrencyStr(int value) {
		DecimalFormat df = new DecimalFormat();
		DecimalFormatSymbols dfs = new DecimalFormatSymbols();
		dfs.setGroupingSeparator('.');
		df.setGroupingSize(3);
		df.setGroupingUsed(true);
		df.setDecimalFormatSymbols(dfs);
		return df.format(value);

	}
	
	private class ViewHolder {
		public TextView tvName, tvBalance;
	}
	
}
